import Editor from "../editor";
import { debounce } from "../utils";
import { event as eventBus } from "../utils";

export class SelectionEvent {
  private _editor: Editor;
  private _container: HTMLElement;
  private _isComposing: boolean;

  constructor (editor: Editor, container: HTMLElement) {
    this._editor = editor;
    this._container = container;
    this._isComposing = false;
  }

  _selectionChangeHandler() {
    if (this._isComposing) return;

    const selection: Selection | null = document.getSelection();
    if (selection != null) {
      this._editor.setSelection(selection.anchorOffset, selection.focusOffset);
    }
  }

  setComposing(status: boolean): void {
    this._isComposing = status;
  }

  addListeners () : void {
    document.addEventListener(
      'selectionchange', 
      debounce(this._selectionChangeHandler.bind(this), 100)
    );
    eventBus.on('set_composing', this.setComposing.bind(this));
  }
}

export default SelectionEvent;